package com.yangxk.kadmin.web.common.datascope;

import com.yangxk.kadmin.common.util.ValidUtil;
import com.yangxk.kadmin.web.common.Const;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 数据权限切面
 *
 * @author yangxk
 * @date 2019/2/2 11:21
 */
@Aspect
@Component
@Slf4j
public class DataScopeAspect {

    @Around("execution(* *..*Service.*(..))")
    public Object dataScope(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Method method = methodSignature.getMethod();
        DataScope annotation = method.getAnnotation(DataScope.class);
        if (annotation != null) {
            DataScopeParam<Long> dataScopeParam = new DataScopeParam<>();
            if (!ValidUtil.isEmpty(annotation.fieldName())) {
                dataScopeParam.setFieldName(annotation.fieldName());
            }
            if (!ValidUtil.isEmpty(annotation.tableAlias())) {
                dataScopeParam.setFieldName(annotation.tableAlias());
            }

            // 从session中获取当前用户的dept_id
            final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            List<Long> ds = (List<Long>) request.getSession().getAttribute(Const.SESSION_USER_DATA_SCOPE_KEY);
            dataScopeParam.setLimitNumbers(ds);

            DataScopeHolder.set(dataScopeParam);
        }

        Object ret = pjp.proceed(pjp.getArgs());

        DataScopeHolder.remove();

        return ret;
    }
}
